<?php
// 该代码块用于接收用户消息，根据用户输入的消息类型进行判断，文本，图片，视频，位置，链接，语音等，并取得值，处理后给予响应。
// 接收用户消息
// 微信公众账号接收到用户的消息类型判断
//

define("TOKEN", "hello1994");

$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else {
    if(isset($_POST['admin'])) {
        $conn=$wechatObj->connectSQL();
        if($conn){
            $wechatObj->updateSQL($conn);
        }
    }else{
        $wechatObj->responseMsg();
    }
}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":    //文本消息
                    $result = $this->receiveText($postObj);
                    break;
                case "image":   //图片消息
                    $result = $this->receiveImage($postObj);
                    break;

                case "voice":   //语音消息
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":   //视频消息
                    $result = $this->receiveVideo($postObj);
                    break;
                case "location"://位置消息
                    $result = $this->receiveLocation($postObj);
                    break;
                case "link":    //链接消息
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "No Xml!";
            exit;
        }
    }

    /*
     * 接收文本消息
     */
    private function receiveText($object)
    {
        $conn = $this->connectSQL();
        if($conn)
        $result = $this->transmitText($object, $conn);
        return $result;
    }
    public function updateSQL($conn)
    {
        $name = $_POST['name'];
        $rank = $_POST['rank'];
        $dbname = "p";

        $sql = "INSERT INTO  players(Name,Rank) VALUES ("."'$name'".","."'$rank')";
        //$sql = "INSERT INTO  players(Name,Rank) VALUES ("."'".utf8_encode($name)."'".","."'".utf8_encode($rank)."'".")";

        if (mysqli_query($conn, $sql)) {
            echo "新记录插入成功";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
    }
    public function querySQL($conn,$name)
    {
		$result="";
		
		
        $sql = "SELECT * FROM "."level25"." WHERE name='$name' ";
        $query = mysqli_query($conn, $sql);
        if ($query->num_rows > 0) {
            // 输出每行数据
            while($row = $query->fetch_assoc()) {
				
				$ft=$row["percent"];
				$ft=sprintf("%.0f", $ft*100);
				$ft.='%';
				
                $result.=  "级别2.5: ". $row["name"]."
排名: ". $row["rank"]."
胜场: ". $row["win"]."
负场: ". $row["lose"]."
一月: ". $row["month1"]."
二月: ". $row["month2"]. "
总分: ". $row["score"]. "
胜率: ". $ft. "
参赛次数: ". $row["count"]."\r\n";
            }
        }
		
		$sql = "SELECT * FROM "."level3"." WHERE name='$name' ";
        $query = mysqli_query($conn, $sql);
        if ($query->num_rows > 0) {
            // 输出每行数据
            while($row = $query->fetch_assoc()) {
				
				$ft=$row["percent"];
				$ft=sprintf("%.0f", $ft*100);
				$ft.='%';
				
                $result.=  "级别3.0: ". $row["name"]."
排名: ". $row["rank"]."
胜场: ". $row["win"]."
负场: ". $row["lose"]."
一月: ". $row["month1"]."
二月: ". $row["month2"]. "
总分: ". $row["score"]. "
胜率: ". $ft. "
参赛次数: ". $row["count"]."\r\n";
            }
        }
		
		$sql = "SELECT * FROM "."level35"." WHERE name='$name' ";
        $query = mysqli_query($conn, $sql);
        if ($query->num_rows > 0) {
            // 输出每行数据
            while($row = $query->fetch_assoc()) {
				
				$ft=$row["percent"];
				$ft=sprintf("%.0f", $ft*100);
				$ft.='%';
				
                $result.=  "级别3.5: ". $row["name"]."
排名: ". $row["rank"]."
胜场: ". $row["win"]."
负场: ". $row["lose"]."
一月: ". $row["month1"]."
二月: ". $row["month2"]. "
总分: ". $row["score"]. "
胜率: ". $ft. "
参赛次数: ". $row["count"]."\r\n";
            }
        }
		return $result;
    }
    public  function connectSQL()
    {
        $servername = "localhost";
        $username = "root";
        $password = "";

// 创建连接
        $conn = mysqli_connect($servername, $username, $password,'wx');
		$conn->query("SET NAMES utf8");
        return $conn;
    }
    /*
     * 接收图片消息
     */
    private function receiveImage($object)
    {
        $content = "你发送的是图片，地址为：".$object->PicUrl;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收语音消息
     */
    private function receiveVoice($object)
    {
        $content = "你发送的是语音，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收视频消息
     */
    private function receiveVideo($object)
    {
        $content = "你发送的是视频，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收位置消息
     */
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收链接消息
     */
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 回复文本消息
     */
    private function transmitText($object, $conn)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $content = $this->querySQL($conn,$object->Content);
        $content = $content ? $content : "未查询到信息";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
}
?>